package com.ys.servers.admin.verticle;

import com.ys.servers.common.mq.InternalEventData;
import com.ys.servers.common.verticle.BasicRestfulVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

/**
 * Created by taotao on 2017/5/31.
 */
public class AdminVerticle extends BasicRestfulVerticle {

    public static final String SERVICE_NAME = "admin-service";
    private String adminKey = null;

    @Override
    protected String interName() {
        return null;
    }

    @Override
    protected void initInternalDispatcher() {

    }

    private static final String POINTS_CLEAR = "/points/:adminKey/:userId/:userType/:pointsTypeId";

    @Override
    public void start(Future<Void> future) throws Exception {

        super.start();
        adminKey = config().getString("admin.key", null);


        final Router router = Router.router(vertx);
        // body handler
        router.route().handler(BodyHandler.create());
        // api route handler

        router.get(POINTS_CLEAR).handler(this::pointsClear);


        String host = config().getString("points.rest.http.address", "0.0.0.0");
        int port = config().getInteger("points.rest.http.port", 18887);

        // create HTTP server and publish REST service
        createHttpServer(router, host, port)
                .compose(serverCreated -> publishHttpEndpoint(SERVICE_NAME, host, port))
                .setHandler(future.completer());
    }

    private void pointsClear(RoutingContext context) {
        String userId = context.request().getParam("userId");
        String key = context.request().getParam("adminKey");
        String userType = context.request().getParam("userType");
        String pointsTypeId = context.request().getParam("pointsTypeId");
        if (null == adminKey) {
            Future<String> future = Future.future();
            future.complete("Admin operations is not Allowed now!");
            future.setHandler(restfulReturnDataHandler(context));
        } else if (!(adminKey.equals(key))) {
            Future<String> future = Future.future();
            future.complete("Admin key is not right, operation is not Allowed !");
            future.setHandler(restfulReturnDataHandler(context));
        } else {
            interService(new InternalEventData()
                    .setParas(new JsonObject().put("userId", userId).put("userType", Integer.parseInt(userType)).put("pointsTypeId", pointsTypeId))
                    .setRecordAddress("points-service").setApiName("clear-points")).setHandler(restfulReturnDataHandler(context));
        }
    }
}
